<template>
    <div class="audio-editor-container">
        <n-card class="audio-card">
            <template #header>
                <div class="card-header">
                    <h1>音频编辑器</h1>
                    <div class="header-actions">
                        <n-button @click="saveAudio" type="primary">
                            <template #icon><n-icon>
                                    <SaveOutline />
                                </n-icon></template>
                            保存音频
                        </n-button>
                        <n-button @click="goBack">
                            <template #icon><n-icon>
                                    <ArrowBackOutline />
                                </n-icon></template>
                            返回
                        </n-button>
                    </div>
                </div>
            </template>

            <div class="audio-content">
                <div class="toolbar">
                    <n-button-group>
                        <n-button @click="play">
                            <template #icon><n-icon>
                                    <PlayOutline />
                                </n-icon></template>
                            播放
                        </n-button>
                        <n-button @click="pause">
                            <template #icon><n-icon>
                                    <PauseOutline />
                                </n-icon></template>
                            暂停
                        </n-button>
                        <n-button @click="stop">
                            <template #icon><n-icon>
                                    <StopOutline />
                                </n-icon></template>
                            停止
                        </n-button>
                    </n-button-group>

                    <n-button-group>
                        <n-button @click="addAudioTrack">
                            <template #icon><n-icon>
                                    <AddOutline />
                                </n-icon></template>
                            添加轨道
                        </n-button>
                        <n-button @click="importAudio">
                            <template #icon><n-icon>
                                    <CloudUploadOutline />
                                </n-icon></template>
                            导入音频
                        </n-button>
                    </n-button-group>

                    <n-select v-model:value="zoomLevel" :options="zoomOptions" size="small" style="width: 100px;" />
                </div>

                <div class="tracks-container">
                    <div v-for="track in audioTracks" :key="track.id" class="audio-track">
                        <div class="track-header">
                            <n-space align="center">
                                <n-checkbox v-model:checked="track.muted">静音</n-checkbox>
                                <n-checkbox v-model:checked="track.solo">独奏</n-checkbox>
                                <span class="track-name">{{ track.name }}</span>
                            </n-space>
                            <n-space>
                                <n-slider v-model:value="track.volume" :min="0" :max="100" style="width: 100px;" />
                                <n-button circle size="small" @click="removeTrack(track.id)">
                                    <template #icon><n-icon>
                                            <CloseOutline />
                                        </n-icon></template>
                                </n-button>
                            </n-space>
                        </div>

                        <div class="track-content">
                            <div class="waveform-container">
                                <div class="time-ruler">
                                    <div v-for="i in 10" :key="i" class="ruler-mark" :style="{ left: `${i * 10}%` }">
                                        <div class="mark-line"></div>
                                        <div class="mark-label">{{ formatTime(i * totalDuration / 10) }}</div>
                                    </div>
                                </div>

                                <div class="waveform">
                                    <div v-for="clip in track.clips" :key="clip.id" class="audio-clip" :style="{
                                        left: `${clip.startTime / totalDuration * 100}%`,
                                        width: `${clip.duration / totalDuration * 100}%`
                                    }" :class="{ 'selected': selectedClip && selectedClip.id === clip.id }"
                                        @click="selectClip(clip, track)">
                                        <div class="clip-handle left" @mousedown="startResizing(clip, 'left', $event)">
                                        </div>
                                        <div class="clip-name">{{ clip.name }}</div>
                                        <div class="clip-handle right"
                                            @mousedown="startResizing(clip, 'right', $event)"></div>
                                    </div>
                                </div>

                                <div class="playhead" :style="{ left: `${currentTime / totalDuration * 100}%` }"></div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="clip-editor" v-if="selectedClip">
                    <h3>音频片段编辑 - {{ selectedClip.name }}</h3>
                    <n-form :model="clipForm" label-placement="left" label-width="100"
                        require-mark-placement="right-hanging">
                        <n-form-item label="片段名称" path="name">
                            <n-input v-model:value="clipForm.name" />
                        </n-form-item>

                        <n-form-item label="开始时间" path="startTime">
                            <n-input-number v-model:value="clipForm.startTime" :min="0" :step="100" />
                        </n-form-item>

                        <n-form-item label="持续时间" path="duration">
                            <n-input-number v-model:value="clipForm.duration" :min="100" :step="100" />
                        </n-form-item>

                        <n-form-item label="音量" path="volume">
                            <n-slider v-model:value="clipForm.volume" :min="0" :max="100" />
                        </n-form-item>

                        <n-form-item label="淡入" path="fadeIn">
                            <n-input-number v-model:value="clipForm.fadeIn" :min="0" :step="100" />
                        </n-form-item>

                        <n-form-item label="淡出" path="fadeOut">
                            <n-input-number v-model:value="clipForm.fadeOut" :min="0" :step="100" />
                        </n-form-item>

                        <n-space justify="end">
                            <n-button @click="updateClip" type="primary">更新</n-button>
                            <n-button @click="deleteClip" type="error">删除</n-button>
                        </n-space>
                    </n-form>
                </div>
            </div>
        </n-card>

        <n-modal v-model:show="importModalVisible" title="导入音频" preset="card" style="width: 600px;">
            <n-form :model="importForm" label-placement="left" label-width="100">
                <n-form-item label="音频文件" path="file">
                    <n-upload action="http://dummy-upload-url" :default-upload="false" @change="handleFileChange">
                        <n-button>选择文件</n-button>
                    </n-upload>
                </n-form-item>

                <n-form-item label="目标轨道" path="trackId">
                    <n-select v-model:value="importForm.trackId" :options="trackOptions" placeholder="选择目标轨道" />
                </n-form-item>

                <n-form-item label="插入位置" path="startTime">
                    <n-input-number v-model:value="importForm.startTime" :min="0" :step="100" />
                </n-form-item>
            </n-form>

            <template #footer>
                <n-space justify="end">
                    <n-button @click="importModalVisible = false">取消</n-button>
                    <n-button type="primary" @click="confirmImport" :disabled="!importForm.file">导入</n-button>
                </n-space>
            </template>
        </n-modal>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useMessage } from 'naive-ui'
import {
    NCard,
    NButton,
    NButtonGroup,
    NIcon,
    NSpace,
    NSlider,
    NCheckbox,
    NSelect,
    NInput,
    NInputNumber,
    NForm,
    NFormItem,
    NModal,
    NUpload
} from 'naive-ui'
import {
    SaveOutline,
    ArrowBackOutline,
    PlayOutline,
    PauseOutline,
    StopOutline,
    AddOutline,
    CloudUploadOutline,
    CloseOutline
} from '@vicons/ionicons5'

const router = useRouter()
const message = useMessage()

// 音频数据
const totalDuration = ref(60000) // 60秒
const currentTime = ref(0)
const zoomLevel = ref(1)

// 选中的音频片段
const selectedClip = ref<any>(null)
const selectedTrack = ref<any>(null)

// 导入模态框
const importModalVisible = ref(false)
const importForm = reactive({
    file: null as File | null,
    trackId: '',
    startTime: 0
})

// 音频轨道数据
const audioTracks = ref([
    {
        id: 'track1',
        name: '背景音乐',
        volume: 80,
        muted: false,
        solo: false,
        clips: [
            {
                id: 'clip1',
                name: '主题曲',
                audioUrl: 'https://example.com/audio1.mp3',
                startTime: 0,
                duration: 20000,
                volume: 80,
                fadeIn: 500,
                fadeOut: 500
            }
        ]
    },
    {
        id: 'track2',
        name: '音效',
        volume: 90,
        muted: false,
        solo: false,
        clips: [
            {
                id: 'clip2',
                name: '脚步声',
                audioUrl: 'https://example.com/audio2.mp3',
                startTime: 5000,
                duration: 3000,
                volume: 70,
                fadeIn: 0,
                fadeOut: 0
            },
            {
                id: 'clip3',
                name: '门响',
                audioUrl: 'https://example.com/audio3.mp3',
                startTime: 15000,
                duration: 2000,
                volume: 90,
                fadeIn: 0,
                fadeOut: 0
            }
        ]
    },
    {
        id: 'track3',
        name: '语音',
        volume: 100,
        muted: false,
        solo: false,
        clips: [
            {
                id: 'clip4',
                name: '旁白',
                audioUrl: 'https://example.com/audio4.mp3',
                startTime: 10000,
                duration: 8000,
                volume: 100,
                fadeIn: 300,
                fadeOut: 300
            }
        ]
    }
])

// 音频片段表单
const clipForm = reactive({
    name: '',
    startTime: 0,
    duration: 0,
    volume: 0,
    fadeIn: 0,
    fadeOut: 0
})

// 轨道选项（用于导入对话框）
const trackOptions = computed(() => {
    return audioTracks.value.map(track => ({
        label: track.name,
        value: track.id
    }))
})

// 缩放选项
const zoomOptions = [
    { label: '50%', value: 0.5 },
    { label: '100%', value: 1 },
    { label: '150%', value: 1.5 },
    { label: '200%', value: 2 }
]

// 格式化时间
const formatTime = (ms: number) => {
    const totalSeconds = Math.floor(ms / 1000)
    const minutes = Math.floor(totalSeconds / 60)
    const seconds = totalSeconds % 60
    return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
}

// 选择音频片段
const selectClip = (clip: any, track: any) => {
    selectedClip.value = clip
    selectedTrack.value = track

    // 更新表单数据
    clipForm.name = clip.name
    clipForm.startTime = clip.startTime
    clipForm.duration = clip.duration
    clipForm.volume = clip.volume
    clipForm.fadeIn = clip.fadeIn
    clipForm.fadeOut = clip.fadeOut

    message.success(`已选择音频片段: ${clip.name}`)
}

// 更新音频片段
const updateClip = () => {
    if (!selectedClip.value) return

    // 更新片段数据
    selectedClip.value.name = clipForm.name
    selectedClip.value.startTime = clipForm.startTime
    selectedClip.value.duration = clipForm.duration
    selectedClip.value.volume = clipForm.volume
    selectedClip.value.fadeIn = clipForm.fadeIn
    selectedClip.value.fadeOut = clipForm.fadeOut

    message.success('音频片段已更新')
}

// 删除音频片段
const deleteClip = () => {
    if (!selectedClip.value || !selectedTrack.value) return

    // 从轨道中删除片段
    const trackIndex = audioTracks.value.findIndex(track => track.id === selectedTrack.value.id)

    if (trackIndex !== -1) {
        audioTracks.value[trackIndex].clips = audioTracks.value[trackIndex].clips.filter(
            clip => clip.id !== selectedClip.value.id
        )
        selectedClip.value = null
        message.success('音频片段已删除')
    }
}

// 添加音频轨道
const addAudioTrack = () => {
    const newTrack = {
        id: `track${audioTracks.value.length + 1}`,
        name: `音频轨道 ${audioTracks.value.length + 1}`,
        volume: 80,
        muted: false,
        solo: false,
        clips: []
    }

    audioTracks.value.push(newTrack)
    message.success('已添加新音频轨道')
}

// 移除音频轨道
const removeTrack = (trackId: string) => {
    const index = audioTracks.value.findIndex(track => track.id === trackId)
    if (index !== -1) {
        audioTracks.value.splice(index, 1)

        // 如果删除的轨道是当前选中的轨道，清除选中状态
        if (selectedTrack.value && selectedTrack.value.id === trackId) {
            selectedClip.value = null
            selectedTrack.value = null
        }

        message.success('已删除音频轨道')
    }
}

// 开始调整片段大小
const startResizing = (clip: any, handle: 'left' | 'right', event: MouseEvent) => {
    message.info(`开始调整片段 ${handle} 边缘`)

    // 实际项目中，这里会实现拖拽调整大小的逻辑
}

// 导入音频相关方法
const handleFileChange = (options: any) => {
    importForm.file = options.file.file
}

const importAudio = () => {
    importModalVisible.value = true
}

const confirmImport = () => {
    if (!importForm.file || !importForm.trackId) {
        message.error('请选择文件和目标轨道')
        return
    }

    // 找到目标轨道
    const targetTrack = audioTracks.value.find(track => track.id === importForm.trackId)
    if (!targetTrack) return

    // 创建新的音频片段
    const newClip = {
        id: `clip${Date.now()}`,
        name: importForm.file.name,
        audioUrl: URL.createObjectURL(importForm.file),
        startTime: importForm.startTime,
        duration: 5000, // 假设文件长度为5秒
        volume: 80,
        fadeIn: 0,
        fadeOut: 0
    }

    // 添加到轨道
    targetTrack.clips.push(newClip)

    // 关闭模态框并清除表单
    importModalVisible.value = false
    importForm.file = null
    importForm.startTime = 0

    message.success('音频已导入')
}

// 播放控制
const play = () => {
    message.success('开始播放')
}

const pause = () => {
    message.success('已暂停')
}

const stop = () => {
    currentTime.value = 0
    message.success('已停止')
}

// 保存音频
const saveAudio = () => {
    message.success('音频设置已保存')
}

// 返回上一页
const goBack = () => {
    router.back()
}

// 生命周期钩子
onMounted(() => {
    // 初始化
})
</script>

<style lang="scss" scoped>
.audio-editor-container {
    padding: 20px;
    height: 100%;
    overflow-y: auto;

    .audio-card {
        .card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;

            h1 {
                margin: 0;
                font-size: 24px;
                font-weight: 500;
            }

            .header-actions {
                display: flex;
                gap: 12px;
            }
        }
    }

    .audio-content {
        display: flex;
        flex-direction: column;
        gap: 16px;

        .toolbar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 8px 0;
        }

        .tracks-container {
            border: 1px solid var(--border-color);
            border-radius: 4px;
            overflow: hidden;

            .audio-track {
                border-bottom: 1px solid var(--border-color);

                &:last-child {
                    border-bottom: none;
                }

                .track-header {
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    padding: 8px 16px;
                    background-color: var(--card-color);
                    border-bottom: 1px solid var(--border-color);

                    .track-name {
                        font-weight: 500;
                        margin-left: 8px;
                    }
                }

                .track-content {
                    position: relative;
                    height: 80px;

                    .waveform-container {
                        position: relative;
                        height: 100%;
                        overflow-x: auto;

                        .time-ruler {
                            height: 20px;
                            background-color: var(--card-color);
                            border-bottom: 1px solid var(--border-color);
                            position: relative;

                            .ruler-mark {
                                position: absolute;
                                height: 100%;

                                .mark-line {
                                    height: 6px;
                                    width: 1px;
                                    background-color: var(--border-color);
                                    position: absolute;
                                    top: 14px;
                                }

                                .mark-label {
                                    font-size: 10px;
                                    color: var(--text-color-secondary);
                                    position: absolute;
                                    top: 0;
                                    transform: translateX(-50%);
                                }
                            }
                        }

                        .waveform {
                            position: relative;
                            height: calc(100% - 20px);
                            background-color: var(--body-color);

                            .audio-clip {
                                position: absolute;
                                height: 40px;
                                top: 50%;
                                transform: translateY(-50%);
                                background-color: rgba(var(--primary-color-rgb), 0.6);
                                border-radius: 4px;
                                cursor: move;

                                &.selected {
                                    outline: 2px solid var(--primary-color);
                                    z-index: 1;
                                }

                                .clip-name {
                                    font-size: 12px;
                                    color: white;
                                    white-space: nowrap;
                                    overflow: hidden;
                                    text-overflow: ellipsis;
                                    padding: 0 8px;
                                    line-height: 40px;
                                }

                                .clip-handle {
                                    position: absolute;
                                    width: 8px;
                                    height: 100%;
                                    top: 0;
                                    background-color: rgba(0, 0, 0, 0.2);
                                    cursor: ew-resize;

                                    &.left {
                                        left: 0;
                                        border-top-left-radius: 4px;
                                        border-bottom-left-radius: 4px;
                                    }

                                    &.right {
                                        right: 0;
                                        border-top-right-radius: 4px;
                                        border-bottom-right-radius: 4px;
                                    }

                                    &:hover {
                                        background-color: rgba(0, 0, 0, 0.3);
                                    }
                                }
                            }
                        }

                        .playhead {
                            position: absolute;
                            top: 0;
                            bottom: 0;
                            width: 2px;
                            background-color: var(--error-color);
                            pointer-events: none;
                        }
                    }
                }
            }
        }

        .clip-editor {
            border: 1px solid var(--border-color);
            border-radius: 4px;
            padding: 16px;

            h3 {
                margin-top: 0;
                margin-bottom: 16px;
                font-size: 16px;
            }
        }
    }
}

/* 响应式调整 */
@media (max-width: 768px) {
    .audio-editor-container {
        padding: 10px;
    }
}
</style>